package org.phoenixframework.api.sys.controller;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.phoenixframework.api.sys.service.ISysAuthorityService;
import org.phoenixframework.api.sys.service.ISysDeptService;
import org.phoenixframework.api.sys.service.ISysUserRoleService;
import org.phoenixframework.api.sys.service.ISysUserService;
import org.phoenixframework.api.sys.util.SecurityUtils;
import org.phoenixframework.common.entity.SysUser;
import org.phoenixframework.common.entity.SysUserRole;
import org.phoenixframework.common.entity.annotation.OperationLog;
import org.phoenixframework.common.entity.base.BaseEntity;
import org.phoenixframework.common.tools.PasswordEncoderUtil;
import org.phoenixframework.common.tools.ResultModel;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 系统用户表 前端控制器
 * </p>
 *
 * @author doublelife
 * @since 2021-05-08
 */
@Slf4j
@Api(tags = {"系统用户"})
@AllArgsConstructor
@RestController
@RequestMapping("/sysUser")
public class SysUserController extends BaseController {

    private final ISysUserService sysUserService;

    private final ISysAuthorityService sysAuthorityService;

    private final ISysUserRoleService sysUserRoleService;

    private final ISysDeptService sysDeptService;

    @OperationLog
    @ApiOperation(value = "获取用户基本信息")
    @GetMapping("/findSysUserInfo")
    public ResultModel<Map<String, Object>> findSysUserInfo() {
        Long userId = SecurityUtils.getUserId();
        Map<String, Object> result = sysUserService.findSysUserInfo(userId);
        return ResultModel.ok(result);
    }

    @OperationLog
    @ApiOperation(value = "获取用户权限")
    @GetMapping("/listAuthorities")
    public ResultModel<?> listAuthorities() {
        List<JSONObject> permissionList = sysAuthorityService.listAuthorities(SecurityUtils.getUserId());
        return ResultModel.map("permissionList", permissionList);
    }

    @OperationLog
    @ApiOperation(value = "获取分页用户列表")
    @GetMapping("/findPage/{current}/{size}")
    public ResultModel<?> findPage(@ApiParam(name = "current", value = "当前页码", required = true)
                                        @PathVariable Long current,
                                        @ApiParam(name = "size", value = "每页记录数", required = true)
                                        @PathVariable Long size,
                                        @ApiParam(name = "sysUserQueryVo", value = "查询对象", required = false)
                                                SysUser sysUserQueryVo) {
        Page<SysUser> sysUserPage = new Page<>(current, size);
        LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.ne(SysUser::getUsername, SecurityUtils.getUsername());
        if (null != sysUserQueryVo.getDeptId() && StringUtils.isNotBlank(sysUserQueryVo.getDeptId().toString())) {
            wrapper.in(SysUser::getDeptId, sysDeptService.findChildrenIds(sysUserQueryVo.getDeptId()));
        }
        wrapper.like(StringUtils.isNotBlank(sysUserQueryVo.getUsername()), SysUser::getUsername, sysUserQueryVo.getUsername());
        wrapper.orderByDesc(BaseEntity::getCreatedDate);
        Page<SysUser> page = sysUserService.page(sysUserPage, wrapper);
        return this.buildByPage(page);
    }

    @OperationLog
    @ApiOperation(value = "保存用户信息")
    @PostMapping("/save")
    public ResultModel<?> save(@ApiParam(name = "sysUser", value = "用户信息", required = true) @Validated @RequestBody SysUser sysUser) {
        sysUser.setPassword(PasswordEncoderUtil.encodeByBCrypt(sysUser.getPassword()));
        boolean result = sysUserService.save(sysUser);
        return this.buildByBool(result);
    }

    @OperationLog
    @ApiOperation(value = "根据id获取一条用户信息")
    @GetMapping("/find/{id}")
    public ResultModel<?> findById(@ApiParam(name = "id", value = "用户Id", required = true) @PathVariable Long id) {
        SysUser sysUser = sysUserService.getById(id);
        sysUser.setPassword(null);
        return this.buildByObject(sysUser);
    }

    @OperationLog
    @ApiOperation(value = "修改用户")
    @PutMapping("/update")
    public ResultModel<?> updateById(@ApiParam(name = "sysUser", value = "用户信息", required = true) @Validated @RequestBody SysUser sysUser) {
        if (StringUtils.isBlank(sysUser.getId().toString())) {
            return ResultModel.error();
        }
        boolean result = sysUserService.updateById(sysUser);
        return this.buildByBool(result);
    }

    @OperationLog
    @ApiOperation(value = "删除用户")
    @DeleteMapping("/remove/{id}")
    public ResultModel<?> removeById(@ApiParam(name = "id", value = "用户Id", required = true) @PathVariable Long id) {
        boolean b = sysUserService.removeById(id);
        return this.buildByBool(b);
    }

    @OperationLog
    @ApiOperation(value = "根据id列表批量删除")
    @DeleteMapping("/removeByIds")
    public ResultModel<?> removeByIds(@RequestBody List<String> ids) {
        boolean b = sysUserService.removeByIds(ids);
        return this.buildByBool(b);
    }

    @OperationLog
    @ApiOperation(value = "根据用户获取角色数据")
    @GetMapping("/findRoles/{userId}")
    public ResultModel<?> findRolesByUserId(@ApiParam(name = "userId", value = "用户Id", required = true) @PathVariable Long userId) {
        Map<String, Object> result = sysUserService.findRolesByUserId(userId);
        return ResultModel.ok(result);
    }

    @OperationLog
    @ApiOperation(value = "为用户分配角色")
    @PostMapping("/setSysRoles")
    public ResultModel<?> setSysRoles(@ApiParam(name = "userId", value = "用户Id", required = true) @RequestParam Long userId,
                                           @ApiParam(name = "roleIds", value = "角色Ids", required = true) @RequestParam List<Long> roleIds) {
        // 先删除
        sysUserRoleService.remove(new LambdaQueryWrapper<SysUserRole>().eq(SysUserRole::getUserId, userId));
        // 保存角色
        ArrayList<SysUserRole> sysUserRoles = new ArrayList<>();
        roleIds.forEach(item -> {
            SysUserRole sysUserRole = new SysUserRole();
            sysUserRole.setUserId(userId);
            sysUserRole.setRoleId(item);
            sysUserRoles.add(sysUserRole);
        });
        boolean b = sysUserRoleService.saveBatch(sysUserRoles);
        return this.buildByBool(b);
    }

}
